<template>
  <div class="authInfo-box">
    <el-container class="container-box">
      <!-- 头部 -->
      <el-header height="auto">
        <el-form
          :inline="true"
          ref="formData"
          :model="formData"
          class="formData-box">
          <el-form-item
            label="授权状态"
            prop="authState">
            <el-select
              v-model="formData.authState"
              placeholder="请选择">
              <el-option
                v-for="(item,index) in searchParamsList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="医院"
            prop="enterpriseId">
            <el-select
              v-model="formData.enterpriseId"
              filterable
              remote
              placeholder="请输入"
              :remote-method="remoteMethod"
              :loading="filterableLoading"
            >
              <el-option
                v-for="item in filterableOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click.stop="onClear(formData)">
              <i class="iconfont el-icon-refresh-right"/>
              重置</el-button>
            <el-button
              type="primary"
              @click.stop="onSubmit"
              :class="{'isAddWidth':submitLoading}"
              :loading="submitLoading"
            >
              <i
                class="iconfont el-icon-search"
                :class="{'isdisplay':submitLoading}" />
              {{ submitLoading?'':'查询' }}</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 内容 -->
      <el-editable
        class="editable-box"
        :data="tableData"
        v-loading="tableLoading"
        height="200px"
        :columns="attrColumns"
      >
        <!-- 序号 -->
        <template
          slot="default-id"
          slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
        <!-- 配送合同 -->
        <template
          slot="default-contract"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="lookContract(scope)"
            type="text">查看</el-button>
        </template>
        <!-- 授权产品 -->
        <template
          slot="default-product"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="lookProduct(scope)"
            type="text">查看</el-button>
        </template>
        <!-- 审核历史 -->
        <template
          slot="default-checkDetails"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="lookDetails(scope)"
            type="text">查看</el-button>
        </template>
        <!-- 操作 -->
        <template
          slot="default-action"
          slot-scope="scope"
          v-if="scope.row.authState === 5">
          <el-button
            size="small"
            @click.stop="toEdit(scope)"
            type="text">编辑</el-button>
          <el-button
            size="small"
            @click.stop="toDelete(scope)"
            type="text text-danger">删除</el-button>
        </template>
      </el-editable>
      <!-- 分页 -->
      <el-pagination
        align="right"
        style="margin-top: 20px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.page"
        :page-size="page.size"
        :page-sizes="PAGE_NUMBER"
        :layout="PAGINATION_LAYOUT"
        :total="page.total"
      />
      <!-- 审核历史 -->
      <el-dialog
        class="areaTab"
        title="审核历史"
        :visible.sync="areaVisible"
        width="800px">
        <el-editable
          class
          :data="tableDatatHistoryVerify"
          height="300px"
          :columns="attrColumnsHistory"
        >
          <template
            slot="default-num"
            slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-editable>
      </el-dialog>
      <!-- 添加申请授权 -->
      <el-dialog
        class="areaTab"
        title="申请授权"
        :visible.sync="isShowAuth"
        @close="handleClose"
        width="600px"
      >
        <el-form
          :rules="typeRules"
          label-width="140px"
          :model="authForm"
          ref="authForm">
          <el-form-item
            label="选择医院"
            prop="enterpriseId">
            <el-select
              :disabled="disabledHospital"
              v-model="authForm.enterpriseId"
              filterable
              remote
              placeholder="请输入"
              :remote-method="remoteMethod"
              :loading="filterableLoading"
            >
              <el-option
                v-for="item in filterableOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="授权有效期"
            prop="time">
            <el-date-picker
              v-model="authForm.time"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item
            label="上传合同书"
            prop="contractUrl">
            <el-upload
              class="dialog-upload"
              action="string"
              :show-file-list="false"
              accept="application/pdf"
              :http-request="toRequest"
              fit="scale-down"
            >
              <div
                class="pdfleft"
                v-if="authForm.contractUrl">
                <i class="iconfont iconpdf" />
                <p>{{ authForm.pdfName }}</p>
              </div>
              <div
                class="tip-box"
                v-if="!authForm.contractUrl">
                <div class="tip-uplader">
                  <i class="el-icon-plus avatar-uploader-icon" />
                </div>
                <p class="tip-font">（支持PDF格式，4M以内）</p>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="合同编号"
            prop="contractCode">
            <el-input
              class="ipt"
              placeholder="请输入"
              v-model="authForm.contractCode"
              clearable />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="onAddAuth">
              <i class="el-icon-circle-check"/>
              提交</el-button>
            <el-button @click="handleClose">
              <i class="el-icon-circle-close"/>
              取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-container>
  </div>
</template>
<script>
import paginationMixin from '@mixins/paginationMixin'
import { fileUpload } from '@const/api'
import ElEditable from '@components/el-editable/index.vue'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import { attrColumns, attrColumnsHistory, searchParamsList } from './const.js'
import { authSupplierHospital, hospitalDownList, DistributorList, historyToexamine } from '@const/beforeSettleApi.js'

import { hasIn } from 'lodash'
const imageLimit = 'application/pdf'
export default {
  name: 'CustomAttr',
  mixins: [paginationMixin],
  components: { ElEditable },
  data () {
    return {
      submitLoading: false,
      disabledHospital: false, // 是否禁用选择医院
      isShowAuth: false, // 申请弹框
      filterableLoading: false, // 医院模糊搜索loading
      filterableOptions: [], // 医院模糊搜索列表
      authForm: {
        // 申请授权数据
        contractUrl: '',
        time: [],
        enterpriseId: '',
        contractCode: ''
      },
      typeRules: {
        // 验证
        enterpriseId: [{ required: true, message: '请选择', trigger: 'change' }],
        time: [{ required: true, message: '请选择', trigger: 'change' }],
        contractCode: [{ required: true, message: '请输入', trigger: 'change' }],
        contractUrl: [
          { required: true, message: '请上传附件', trigger: 'change' }
        ]
      },

      attrColumnsHistory, // 历史审核表头
      tableDatatHistoryVerify: [], // 历史审核数据
      areaVisible: false, // 是否显示审核历史弹框

      // 查询的条件数据
      formData: {
        authState: '',
        enterpriseName: ''
      },
      attrColumns, // 列表表头信息
      tableData: [], // 列表数据
      searchParamsList, // 授权状态的下拉内容
      tableLoading: false,

      PAGE_NUMBER, // 页码
      PAGINATION_LAYOUT // 分页功能
    }
  },
  created () {
    this.initNavButtons()
    this.getList()
    this.remoteMethod('')
  },
  methods: {
    //   编辑
    toEdit (e) {
      this.disabledHospital = true
      this.isShowAuth = true
      this.$nextTick(() => {
        this.authForm.enterpriseId = e.row.enterpriseName
        this.authForm.time = [e.row.validityFrom, e.row.validityFrom]
        this.authForm.contractUrl = e.row.contractUrl
        this.authForm.pdfName = e.row.contractName
        this.authForm.contractCode = e.row.contractCode || ''
        this.authForm.id = e.row.id
      })
    },
    // 取消
    handleClose () {
      this.$refs['authForm'].resetFields()
      this.remoteMethod('')
      this.isShowAuth = false
    },
    //   删除
    toDelete (e) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios
            .$delete(authSupplierHospital, {
              params: {
                id: e.row.id
              }
            })
            .then(res => {
              this.$message({ type: 'success', message: '删除成功' })
              this.getList()
            })
            .finally(res => {})
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 模糊搜索医院下拉
    remoteMethod (val) {
      // if (val) {
      this.filterableLoading = true
      this.$axios
        .$get(hospitalDownList, {
          params: {
            name: val,
            type: 'hospital'
          }
        })
        .then(res => {
          this.filterableLoading = false
          this.filterableOptions = hasIn(res, 'payload') ? res.payload : []
        })
        .finally(res => {})
      // } else {
      //   this.filterableOptions = []
      // }
    },
    // 提交申请
    onAddAuth () {
      this.$refs['authForm'].validate(valid => {
        if (valid) {
          let data = {
            validityFrom: this.authForm.time[0],
            validityTo: this.authForm.time[1],
            contractUrl: this.authForm.contractUrl,
            contractName: this.authForm.pdfName,
            contractCode: this.authForm.contractCode
          }
          if (this.authForm.id) {
            // 编辑
            this.$axios
              .$put(authSupplierHospital + '?id=' + this.authForm.id, data)
              .then(res => {
                if (res.code === '0') {
                  this.$message({ type: 'success', message: '编辑成功' })
                  this.isShowAuth = false
                  this.getList()
                }
              })
          } else {
            // 新增
            data.enterpriseId = this.authForm.enterpriseId
            this.$axios
              .$post(authSupplierHospital + '?flag=list', data)
              .then(res => {
                if (res.code === '0') {
                  this.$message({ type: 'success', message: '申请成功' })
                  this.isShowAuth = false
                  this.getList()
                }
              })
          }
        }
      })
      // this.filterableOptions = []
    },
    // 查看配送合同
    lookContract (e) {
      this.$pdfViewer({ url: e.row.contractUrl, title: '配送合同' })
    },
    // 查看授权产品
    lookProduct (e) {
      // console.log(e)
      this.$router.push({
        path:
          '/distributorSide/channelManagement/applyHospitaAuth/addProduct',
        query: {
          id: e.row.id,
          name: e.row.enterpriseName,
          enterpriseId: e.row.enterpriseId,
          authState: e.row.authState,
          validityTo: e.row.validityTo, // 合同有效期
          user: e.row.contactName, // 合同有效期
          phone: e.row.contactNumber// 合同有效期
        }
      })
    },
    // 上传pdf
    toRequest (dataA) {
      // 拦截
      const isJPG = imageLimit.includes(
        dataA.file.name.replace(/.+\./, '').toLowerCase()
      )
      if (!isJPG) {
        this.$message.error('上传证照只能是PDF格式!')
        return false
      }
      const isLt2M = dataA.file.size / 1024 / 1024 < 4
      if (!isLt2M) {
        this.$message.error('上传附件大小不能超过4M!')
        return false
      }
      // 发起请求
      let fd = new FormData()
      fd.append('file', dataA.file)
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      }).then(res => {
        this.$message({ type: 'success', message: '上传成功', duration: 1000 })
        this.authForm.contractUrl = res.data.payload
        this.authForm.pdfName = dataA.file.name
        this.$refs['authForm'].clearValidate('contractUrl')
      })
    },
    // 获取数据列表
    getList () {
      this.tableLoading = true
      this.submitLoading = true
      this.$axios
        .$get(DistributorList, {
          params: {
            ...this.formData,
            page: this.page.page,
            size: this.page.size,
            type: 2
          }
        })
        .then(res => {
          this.tableData = hasIn(res, 'payload.content')
            ? res.payload.content
            : []

          this.page.total = hasIn(res, 'payload.totalElements')
            ? res.payload.totalElements
            : 0
        })
        .finally(res => {
          this.submitLoading = false
          this.tableLoading = false
        })
    },
    // 查询
    onSubmit () {
      this.page.page = 1
      this.getList()
    },
    // 重置
    onClear () {
      this.$refs['formData'].resetFields()
      // this.filterableOptions = []
    },
    // 查看明细查看历史审核
    lookDetails (e) {
      this.areaVisible = true
      this.$axios
        .$get(historyToexamine, {
          params: {
            authId: e.row.id,
            authType: 1
          }
        })
        .then(res => {
          this.tableDatatHistoryVerify = hasIn(res, 'payload')
            ? res.payload
            : []
        })
    },
    // 申请授权
    toAuth () {
      this.isShowAuth = true
      this.remoteMethod('')
      // this.filterableOptions = []
    },
    // 初始化 导航栏 按钮组
    initNavButtons () {
      let obj = {
        type: 'btn',
        arr: [
          {
            val: '申请授权',
            type: 'primary',
            handle: this.toAuth
          }
        ]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    // 分页
    handleSizeChange (size) {
      this.page.size = size
      this.getList()
    },
    handleCurrentChange (curPage) {
      this.page.page = curPage
      this.getList()
    }
  }
}
</script>
<style lang="less">
.authInfo-box {
  .container-box {
    height: 100%;
    overflow: auto;
  }

  .pagination {
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 0;
  }

  .tip-box {
    border: 1px solid #ccc;
    padding: 5px;

    .tip-uplader {
      width: 50px;
      height: 50px;
      border: 1px solid #ccc;
      border-radius: 50%;
      margin: 10px auto;
      line-height: 50px;
      font-size: 18px;
    }

    .tip-font {
      font-size: 12px;
      color: #aaa;
    }
  }

  .ipt {
    width: 211px;
  }

  .pdfleft i {
    font-size: 50px;
  }
}
</style>
